<template>
  <div class="upload-container">
    <el-upload
      class="image-uploader"
      ref="upload"
      :data="dataObj"
      :drag="drag"
      :multiple="multiple"
      show-file-list
      :list-type="listType"
      :accept="accept"
      :action="action"
      :file-list="fileList"
      auto-upload
      :before-upload="beforeUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      with-credentials
      :on-success="handleImageScucess">
      <i class="el-icon-upload"></i>
      <i class="el-icon-plus"></i>
      <div slot="tip" class="el-upload__tip">最多只能上传 {{fileMaxNum}} 张jpg/png格式图片，且不超过{{fileMaxSize}}kb</div>
    </el-upload>
  </div>
</template>

<script>
// import { getToken } from '@/api/base/qiniu'
import { Message } from 'element-ui'
import { req } from '@/api/base/BaseApi'
export default {
  name: 'Upload',
  props: {
    value: String | Array,
    accept: {
      type: String,
      default: 'image/*'
    },
    fileMaxNum: {
      type: Number,
      default: 1
    },
    fileMaxSize: {
      type: Number,
      default: 100
    },
    action: String,
    multiple: {
      type: Boolean,
      default: false
    },
    listType: {
      type: String,
      default: 'picture-card'
    },
    drag: {
      type: Boolean,
      default: false
    },
    fileUrl: {
      type: String,
      default: ''
    }
  },
  computed: {
    imageUrl() {
      return this.value
    }
  },
  data() {
    return {
      tempUrl: '',
      fileNum: 0,
      fileList: [],
      dataObj: { token: '', key: '' }
    }
  },
  watch: {
    value(val, oldVal) { // 普通的watch监听
      if (val && typeof val === 'object') {
        this.fileNum = val.length
        this.fileList = []
        val.forEach(f => {
          if (f.substring(0, 4) === 'http') {
            this.fileList.push({ url: f })
          } else {
            req('/api/sys/open/file/' + f, 'get').then(res => {
              const d = res.data
              if (res.code === 200) {
                if (d.url.substring(0, 4) === 'http') {
                  this.fileList.push(d)
                } else {
                  this.fileList.push({ id: f, url: this.fileUrl + f })
                }
              }
            }).catch(err => {
              console.log(err)
            })
          }
        })
      } else {
        if (val) {
          if (val.substring(0, 4) === 'http') {
            this.fileList.push({ url: val })
          } else {
            req('/api/sys/open/file/' + val, 'get').then(res => {
              const d = res.data
              if (res.code === 200) {
                if (d.url.substring(0, 4) === 'http') {
                  this.fileList = [d]
                } else {
                  this.fileList = [{ id: val, url: this.fileUrl + val }]
                }
              }
            }).catch(err => {
              console.log(err)
            })
          }
          this.fileNum = 1
        }
      }
      // 把图片地址回传
      this.emitScucess(null, null, this.fileList)
    }
  },
  methods: {
    emitScucess(val, file, fileList) {
      this.$emit('scucess', val, file, fileList)
    },
    emitRemove(val) {
      this.$emit('remove', val)
    },
    emitPreview(val) {
      this.$emit('preview', val)
    },
    emitResult(val) {
      this.$emit('result', val)
    },
    handleImageScucess(response, file, fileList) {
      this.emitScucess(response, file, fileList)
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.fileNum = this.fileList.length
      this.emitRemove(file, fileList)
    },
    handlePreview(file) {
      this.emitPreview(file)
    },
    beforeUpload(file) {
      if (this.fileNum >= this.fileMaxNum) {
        Message({
          message: '文件已达最大数量( ' + this.fileMaxNum + ' )',
          type: 'error',
          duration: 5 * 1000
        })
        return false
      }
      if (file.size > this.fileMaxSize * 1024) {
        Message({
          message: '文件大小超过限( ' + this.fileMaxSize + 'KB )',
          type: 'error',
          duration: 5 * 1000
        })
        return false
      }
    },
    submitUpload() {
      this.$refs.upload.submit()
    }
    /*
    beforeUpload() {
      const _self = this
      return new Promise((resolve, reject) => {
        getToken().then(response => {
          const key = response.data.qiniu_key
          const token = response.data.qiniu_token
          _self._data.dataObj.token = token
          _self._data.dataObj.key = key
          this.tempUrl = response.data.qiniu_url
          this.emitResult(this.tempUrl)
          resolve(true)
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      })
    }
    */
  }
}
</script>
